package com.moli.java.thread;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @program: JavaQuesDemo
 * @description: 线程池拒绝策略
 * @author: zhangjt
 * @create: 2024-11-19 11:42
 **/
public class ThreadPoolExample {
    public static void main(String[] args) {
        // 创建一个线程池，核心线程数为 2，最大线程数为 4，队列大小为 2
        // 线程池的拒绝策略为 AbortPolicy，即直接抛出异常
        /*
        *
        * CallerRunsPolicy: 如果你不希望任务被拒绝，可以将拒绝策略改为 CallerRunsPolicy，这样任务会在提交者线程中执行：
            new ThreadPoolExecutor.CallerRunsPolicy()
          DiscardPolicy: 如果你不希望任务抛出异常，可以将拒绝策略改为 DiscardPolicy，这会直接丢弃超出的任务：
            new ThreadPoolExecutor.DiscardPolicy()
          DiscardOldestPolicy: 如果你希望丢弃队列中最旧的任务，可以将拒绝策略改为 DiscardOldestPolicy，并重新提交当前任务：
            new ThreadPoolExecutor.DiscardOldestPolicy()
        * */
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(5),
                new ThreadPoolExecutor.AbortPolicy());

        // 提交 5 个任务
        for (int i = 0; i < 5; i++) {
            final int taskId = i;
                threadPoolExecutor.submit(() -> {
                        System.out.println("Task " + taskId + " started by " + Thread.currentThread().getName());
                    try {
                        Thread.sleep(10000);  // 模拟任务处理
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("Task " + taskId + " finished by " + Thread.currentThread().getName());
                });

        }

        // 关闭线程池
        threadPoolExecutor.shutdown();
    }
}
